<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input v-model="queryParams.keywords" placeholder="关键字" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" clearable style="width: 100px">
            <el-option v-for="item in InventoryType" :key="item" :label="Inventory_LABEL[item]" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="queryParams.warehouseId" placeholder="仓库" style="width: 100px">
            <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id || ''" />
          </el-select>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button type="primary" plain icon="plus" @click="gotoOperation('in')">
            材料入库
          </el-button>
          <el-button type="primary" plain icon="remove" @click="gotoOperation('out')">
            材料出库
          </el-button>
          <el-button type="primary" plain icon="plus" @click="showConfigSaleMeal">
            配置套餐
          </el-button>
        </div>
      </div>

      <el-table ref="dataTableRef" v-loading="loading" :data="tableDatas" highlight-current-row border
        class="data-table__content">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="仓库名称" prop="warehouseName" width="150" />
        <el-table-column label="材料名称" prop="name" width="150" />
        <el-table-column label="材料类型" width="150">
          <template #default="scope">
            {{ Inventory_LABEL[scope.row.type] }}
          </template>
        </el-table-column>
        <el-table-column label="材料编码" prop="sku" width="150" />
        <el-table-column label="规格" align="center" min-width="150" prop="spec" />
        <el-table-column label="数量" align="center" min-width="80" prop="quantity">
          <template #default="scope">
            <span v-if="scope.row.quantity < 10" style="color: red">{{ scope.row.quantity }}</span>
            <span v-else style="color: green">{{ scope.row.quantity }}</span>
          </template>
        </el-table-column>
        <el-table-column label="锁定数" align="center" min-width="80" prop="quantity">
          <template #default="scope">
            <span style="color: red">{{ scope.row.lockQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column label="市场价" align="center" min-width="80" prop="price" />
        <el-table-column label="成本价" align="center" min-width="80" prop="costPrice" />
        <el-table-column label="单位" align="center" min-width="80" prop="unit" />
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="fetchData" />
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" @close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" label-width="100px" :rules="rules">
        <el-form-item label="选择套餐" prop="saleMealId">
          <el-select v-model="formData.saleMealId" placeholder="请选择套餐" @change="handleSaleMealChange">
            <el-option v-for="item in saleMealList" :key="item.id" :label="item.name" :value="item.id || ''" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作" prop="operation">
          <el-radio-group v-model="formData.operation" @change="formData.quantity = 0">
            <el-radio :label="0">增加</el-radio>
            <el-radio :label="1">减少</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="formData.quantity" :precision="0" :step="1" :min="0" :max="0 ||
        formData.operation === 0 ? maxAddSaleMealNum : maxSubSaleMealNum
        " style="width: 200px"></el-input-number>
        </el-form-item>
        <el-form-item>
          最大添加数量：{{ maxAddSaleMealNum }}, 最多减少数量：{{ maxSubSaleMealNum }}
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { useAppStore } from "@/store/modules/app.store";
import router from "@/router";

import type { ElTable } from "element-plus";
const dataTableRef = ref<InstanceType<typeof ElTable>>();

import WarehouseAPI, { WarehousePageVO } from "@/api/business/warehouse/warehouse.api";
import InventoryAPI, {
  InventoryPageQuery,
  InventoryPageVO,
  ConfigSaleMealForm,
  Inventory_LABEL,
  InventoryType
} from "@/api/business/warehouse/inventory.api";
import SealMealAPI, { SealMealPageVO } from "@/api/business/material/sealMeal.api";
defineOptions({
  name: "Inventory",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryParams = reactive<InventoryPageQuery>({
  pageNum: 1,
  pageSize: 10,
});
// 客户表单
const formData = reactive<ConfigSaleMealForm>({
  quantity: 0,
  warehouseId: queryParams.warehouseId,
  operation: 0,
});
const queryFormRef = ref();
const formRef = ref();
const loading = ref(false);
const total = ref(0);
const warehouseList = reactive<WarehousePageVO[]>([]);
const saleMealList = reactive<SealMealPageVO[]>([]);
const maxAddSaleMealNum = ref(0);
const maxSubSaleMealNum = ref(0);

// 客户表格数据
const tableDatas = ref<InventoryPageVO[]>();

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

function gotoOperation(type?: string) {
  if (type == "out") {
    router.push({
      path: "/warehouse/outOperation",
      query: { title: "材料出库" },
    });
  } else {
    router.push({
      path: "/warehouse/inOperation",
      query: { title: "材料入库" },
    });
  }
}

async function showConfigSaleMeal() {
  dialog.title = "配置套餐";
  await SealMealAPI.loadConfigAll(queryParams.warehouseId)
    .then((data) => {
      saleMealList.splice(0);
      saleMealList.push(...data);
    })
    .finally(() => {
      dialog.visible = true;
    });
}

async function handleSaleMealChange() {
  maxAddSaleMealNum.value = saleMealList.filter((item) => item.id == formData.saleMealId)
    .map((item) => item.maxConfigNum)[0] || 0;
  let saleMealVentory = await InventoryAPI.loadByMaterial(formData.saleMealId!,
    queryParams.warehouseId, InventoryType.SALE_MEAL);
  maxSubSaleMealNum.value = saleMealVentory?.quantity || 0;

}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formRef.value.resetFields();
  formRef.value.clearValidate();
  maxAddSaleMealNum.value = 0;
  maxSubSaleMealNum.value = 0;
}

function handleSubmit() {
  if (!formData.quantity || formData.quantity <= 0) {
    ElMessage.warning("套餐配置数量不足");
    return;
  }
  formRef.value.validate((valid: any) => {
    InventoryAPI.configSaleMeal(formData)
      .then(() => {
        ElMessage.success("配置成功");
        handleCloseDialog();
        handleResetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

// 获取数据
function fetchData() {
  loading.value = true;
  InventoryAPI.getPage(queryParams)
    .then((data) => {
      tableDatas.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

// 删除客户
function handleDelete(roleId: string) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    WarehouseAPI.deleteById(roleId)
      .then(() => {
        ElMessage.success("删除成功");
        handleResetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

const loadWarehouses = () => {
  WarehouseAPI.loadAll().then((data) => {
    if (data.length > 0) {
      warehouseList.push(...data);
      queryParams.warehouseId = data[0].id;
    }
  });
};

const rules = reactive({
  saleMealId: [{ required: true, message: "套餐不能为空", trigger: "blur" }],
  quantity: [{ required: true, message: "套餐数量不能为空", trigger: "blur" }],
});

onMounted(() => {
  loadWarehouses();
  handleQuery();
});
</script>
